package com.vcc.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.vcc.core.util.RedisCustomizeUtils;
import com.vcc.data.entity.BossRolePermission;
import com.vcc.data.mapper.BossRolePermissionMapper;
import com.vcc.service.boss.request.permission.PermissionDto;
import com.vcc.service.service.BossRolePermissionService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BossRolePermissionServiceImpl extends ServiceImpl<BossRolePermissionMapper, BossRolePermission> implements BossRolePermissionService {
    @Override
    public List<BossRolePermission> listByBossRoleId(Long bossRoleId) {
        return queryChain().eq(BossRolePermission::getBossRoleId, bossRoleId).list();
    }

    @Override
    public List<BossRolePermission> listByUserId(Long userId) {
        String key = "user_role_permission:" + userId;
        if (RedisCustomizeUtils.hasKey(key)) {
            return RedisCustomizeUtils.getList(key, BossRolePermission.class);
        }
        List<BossRolePermission> list = mapper.findAllByUserId(userId);
        RedisCustomizeUtils.set(key, list, 5L, TimeUnit.MINUTES);
        return list;
    }


    @Override
    public Boolean updateRolePermission(Long roleId, List<PermissionDto> list) {
        List<BossRolePermission> bossRolePermissions = listByBossRoleId(roleId);
        for (BossRolePermission bossRolePermission : bossRolePermissions) {
            list.forEach(permissionDto -> {
                if (!queryChain().eq(BossRolePermission::getBossRoleId, roleId).eq(BossRolePermission::getPermissionId, permissionDto.getId()).exists()) {
                    BossRolePermission bossRolePermission1 = new BossRolePermission();
                    bossRolePermission1.setBossRoleId(roleId);
                    bossRolePermission1.setPermissionId(permissionDto.getId());
                    bossRolePermission1.setStatus(permissionDto.getStatus());
                    save(bossRolePermission1);
                } else {
                    if (bossRolePermission.getPermissionId().equals(permissionDto.getId())) {
                        updateChain().set(BossRolePermission::getStatus, permissionDto.getStatus()).eq(BossRolePermission::getId, bossRolePermission.getId()).update();
                    }
                }
            });
        }
        return true;
    }


    @Override
    public Boolean removeByRoleId(Long roleId) {
        return remove(queryChain().eq(BossRolePermission::getBossRoleId, roleId));
    }

    @Override
    public Boolean removeByPermissionIdAndBossUserId(Long permissionId, Long bossUserId) {
        QueryChain<BossRolePermission> queryChain = queryChain();
        queryChain.eq(BossRolePermission::getPermissionId, permissionId);
        queryChain.eq(BossRolePermission::getBossRoleId, bossUserId);
        return remove(queryChain);
    }
}
